//
//  MyAppsListController.m
//  PgyHelper
//
//  Created by 鹏鹏 on 2020/11/12.
//  Copyright © 2020 CleverPeng. All rights reserved.
//

#import "MyAppsListController.h"
#import "RequestTool.h"
#import "MyAppTableViewCell.h"
#import "DetailViewController.h"
#import "AccountViewController.h"

@interface MyAppsListController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *appsList;

@end

@implementation MyAppsListController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if ([RequestTool get_api_key].length == 0) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"api_key检测" message:@"未获取到api_key, 请先配置! 否则无法使用APP" preferredStyle:UIAlertControllerStyleAlert];
        WEAKSELF
        [alertVC addAction:[UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            abort();
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf dealWithAccount:nil];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];

    } else {
        [self.tableView.mj_header beginRefreshing];
    }
}

- (NSMutableArray *)appsList {
    if (nil == _appsList) {
        _appsList = [NSMutableArray array];
    }
    return _appsList;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }

    [self loadNavigationItem];
    [self loadMainView];
}

- (void)loadNavigationItem {
    UIBarButtonItem *accountItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"account"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(dealWithAccount:)];
    self.navigationItem.rightBarButtonItem = accountItem;
}

- (void)dealWithAccount: (UIBarButtonItem *)sender {

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //故事板界面跳转
    //从Storyboard中通过一个标识取出一个场景,返回的是场景绑定的VC实例
    // 根据id 获取一个界面 从故事板
    AccountViewController *accountVC = [storyboard instantiateViewControllerWithIdentifier:@"story_accountVC"];
    [self.navigationController pushViewController:accountVC animated:YES];
}

- (void)loadMainView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MyAppTableViewCell class]) bundle:nil] forCellReuseIdentifier:cellIdentifier];
    [self.view addSubview:tableView];
    self.tableView = tableView;

    tableView.tableFooterView = [UIView new];

    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.equalTo(self.view.mas_bottomMargin).with.offset(-10);
    }];

    MJWeakSelf
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf queryAppsList];
    }];
}

- (IBAction)refreshData:(id)sender {
    [self.tableView.mj_header beginRefreshing];
}

- (void)queryAppsList {
    NSString *params = [NSString stringWithFormat:@"_api_key=%@", [RequestTool get_api_key]];

    WEAKSELF
    [RequestTool postWith:HOST_URL_app_listMy paramsString:params completeHandler:^(NSString * _Nullable responseString, NSDictionary * _Nullable responseDataDic, BOOL isSuccess, NSString * _Nullable message) {
        [weakSelf.tableView.mj_header endRefreshing];
        if (!isSuccess) {
            [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:message afterDelay:1.5];
            return;
        }

        if (nil == responseDataDic) {
            [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:@"数据异常" afterDelay:1.5];
            return;
        }

        NSArray *list = responseDataDic[@"list"];
        [weakSelf.appsList removeAllObjects];
        NSArray *models = [NSArray yy_modelArrayWithClass:[MyAppModel class] json:list];
        [weakSelf.appsList addObjectsFromArray:models];

        [weakSelf.tableView reloadData];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.appsList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

static NSString *cellIdentifier = @"MyAppTableViewCell";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MyAppTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    MyAppModel *appModel = self.appsList[indexPath.section];
    cell.appModel = appModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    MyAppModel *appModel = self.appsList[indexPath.section];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //故事板界面跳转
    //从Storyboard中通过一个标识取出一个场景,返回的是场景绑定的VC实例
    // 根据id 获取一个界面 从故事板
    DetailViewController *detailVC = [storyboard instantiateViewControllerWithIdentifier:@"story_detailVC"];
    detailVC.appModel = appModel;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return  UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

@end
